package models

import (
	"gorm.io/gorm"
)

type Xshuo struct {
	gorm.Model
	Name    string `gorm:"type:varchar(30)" json:"name"`
	Content string `gorm:"type:varchar(30)" json:"content"`
	Img     string `gorm:"type:varchar(100)" json:"img"`
}

func (x *Xshuo) Update() error {
	return DB.Where("id = ?", x.ID).Updates(&x).Error
}

func (x *Xshuo) Del() error {
	return DB.Delete(&x).Error
}

func (x *Xshuo) Get() error {
	return DB.Where("name = ?", x.Name).Limit(1).Find(&x).Error
}

func (x *Xshuo) Create() error {
	return DB.Create(&x).Error
}

func (x *Xshuo) List(keyword string, page, pageSize int) (list []*Xshuo, err error) {
	err = DB.Where("name like ?", "%"+keyword+"%").Scopes(Paginate(page, pageSize)).Find(&list).Error
	return
}
func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {

		if page <= 0 {
			page = 1
		}

		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}
